package com.wzt.lianfirecontrol.fragment;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.activity.ActivityCollecter;
import com.wzt.lianfirecontrol.activity.BaseActivity;
import com.wzt.lianfirecontrol.activity.LoginActivity;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongDeviceModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongFloorModel;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.PreferencesUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.WebViewSettingUtils;
import com.wzt.lianfirecontrol.view.GetTopWebView;
import com.wzt.lianfirecontrol.view.InitView;
import com.wzt.lianfirecontrol.view.SuperSwipeRefreshLayout;

import org.json.JSONObject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 视频监控
 */
public class WebCadFragment extends BaseFragment implements SuperSwipeRefreshLayout.OnSwipeRefreshListener {
    private BaseActivity activity;
    private View itemContentView;

    private View include_head_title;

    private SuperSwipeRefreshLayout swipeLayout;
    private WebView webview;
    private WebViewClient webViewClient;
    private WebChromeClient webChromeClient;

    private Bundle bundle;
    private String url;

    private JianKongFloorModel jianKongFloorModel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == itemContentView){
            activity = getMyActivity();
            bundle = getArguments();
            if (null != bundle){
                url = bundle.getString("url");
                jianKongFloorModel = (JianKongFloorModel) bundle.getSerializable("jianKongFloorModel");
            }
            url = "file:///android_asset/cad/index2.html";
            //url = "http://134.175.220.20/leaflet/index2.html";
            itemContentView = inflater.inflate(R.layout.f_web, container, false);
            initView();
        }
        if (itemContentView.getParent() != null) {
            ((ViewGroup) itemContentView.getParent()).removeView(itemContentView);
        }
        return itemContentView;
    }

    private void initView() {
        initHeadView();
        swipeLayout = itemContentView.findViewById(R.id.swipe_container);
        swipeLayout.setOnSwipeRefreshListener(this);

        webview = (GetTopWebView) itemContentView.findViewById(R.id.gtwv_web);
        if (url.contains("needRefresh=0")){
            swipeLayout.setEnabled(false);
            ((GetTopWebView)webview).setNeedRefresh(false);
        }else {
            InitView.instance().initSuperSwipeLayout(swipeLayout);
        }
        webview.setVerticalScrollbarOverlay(false);
        ((GetTopWebView)webview).setSwipeRefreshLayout(swipeLayout);
        webview.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
        initWebView();

        if (!StringUtils.isEmpty(url)){
            webview.loadUrl(url);
        }
    }

    private void initHeadView() {
        include_head_title = itemContentView.findViewById(R.id.include_head_title);
        include_head_title.setVisibility(View.GONE);
    }

    /**
     * 初始化webview
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview = WebViewSettingUtils.getSettingInstance(webview, activity);
        webChromeClient = new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                swipeLayout.setRefreshing(false);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                // TODO Auto-generated method stub
                return super.onJsAlert(view, url, message, result);
            }
        };
        webview.setWebChromeClient(webChromeClient);
        WebViewClient webViewClient = new BridgeWebViewClient((BridgeWebView) webview) {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.e("startUrl", url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.e("shouldOverrideUrl", url);
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e("finishUrl", url);
                webview.loadUrl("JavaScript:bridgeData2(\"" + jianKongFloorModel.getBuildingId()
                        + "\",\"" +  jianKongFloorModel.getId()
                        + "\",\"" +  jianKongFloorModel.getCadUri()
                        + "\",\"" + Url.URL_CONTENT
                        + "\",\"" + Url.POST
                        + "\",\"" +  UserInfoModel.getUserToken(activity)
                        + "\",\"" +  UserInfoModel.getCompandId(activity) + "\")");
                Log.e("wb","JavaScript:bridgeData2(\"" + jianKongFloorModel.getBuildingId()
                        + "\",\"" +  jianKongFloorModel.getId()
                        + "\",\"" +  jianKongFloorModel.getCadUri()
                        + "\",\"" + Url.URL_CONTENT
                        + "\",\"" + Url.POST
                        + "\",\"" +  UserInfoModel.getUserToken(activity)
                        + "\",\"" +  UserInfoModel.getCompandId(activity) + "\")");

            }
        };
        webview.setWebViewClient(webViewClient);

        setJsBridge();
    }

    private void setJsBridge() {
        if (webview instanceof GetTopWebView) {

            //注册showToast方法
            ((GetTopWebView) webview).registerHandler("showToast", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    if (StringUtils.isEmpty(data)) {
                        function.onCallBack("数据不能为空");
                        return;
                    }
                    ToastUtils.showToast(activity, data);
                    function.onCallBack("toast成功");
                }
            });

            //返回
            ((GetTopWebView) webview).registerHandler("doBack", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (null != webview && webview.canGoBack()) {
                            webview.goBack();
                        }
                        function.onCallBack(" 返回成功");
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });

            //注册关闭网页方法
            ((GetTopWebView) webview).registerHandler("closeWeb", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        activity.finish();
                    } catch (Exception e) {
                        function.onCallBack(" 返回失败");
                    }
                }
            });

            //注册修改preference值方法
            ((GetTopWebView) webview).registerHandler("changePreference", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        if (!StringUtils.isEmpty(data)) {
                            String[] keyValue = data.split(",");
                            PreferencesUtils.putString(activity, keyValue[0], keyValue[1]);
                            function.onCallBack(" 修改成功");
                        } else {
                            function.onCallBack(" data不能为空");
                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败");
                    }
                }
            });

            //注册退出登录方法
            ((GetTopWebView) webview).registerHandler("exitAccount", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        UserInfoModel.clearUserLoginMessage(activity);
                        ActivityCollecter.finishAllActivitys();
                        Bundle bundle1 = new Bundle();
                        if (!StringUtils.isEmpty(data)) {
                            bundle1.putString("error_msg", data);
                        }
                        activity.openActivity(LoginActivity.class, bundle1, 0);
                        function.onCallBack(" 退出成功");
                    } catch (Exception e) {
                        function.onCallBack(" 退出失败");
                    }
                }
            });

            //注册刷新方法
            ((GetTopWebView) webview).registerHandler("refreshCurrentPage", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    try {
                        webview.reload();
                    } catch (Exception e) {
                        function.onCallBack(" 跳转失败");
                    }
                }
            });

            //获取token
            ((GetTopWebView) webview).registerHandler("getToken", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    function.onCallBack(UserInfoModel.getUserToken(activity));
                }
            });

            //跳转到监控设备详情
            ((GetTopWebView) webview).registerHandler("skipToVideoDetail", new BridgeHandler() {
                @Override
                public void handler(String data, CallBackFunction function) {
                    Log.e("data",   data.toString());

                    try {
                        JianKongDeviceModel jianKongDeviceModel = JSONUtil.jsonObjectToBean(new JSONObject(data), JianKongDeviceModel.class);
                        bundle.putSerializable("JianKongDeviceModel", jianKongDeviceModel);
                        activity.setClickAction(ConstData.VIDEO, jianKongDeviceModel.getAccessMode(), "监控设备", null, bundle);
//                        if (!StringUtils.isEmpty(data)) {
//                            JianKongDeviceModel jianKongDeviceModel = JSONUtil.jsonObjectToBean(new JSONObject(data), JianKongDeviceModel.class);
//                            bundle.putSerializable("JianKongDeviceModel", jianKongDeviceModel);
//                            activity.setClickAction(ConstData.VIDEO, jianKongDeviceModel.getAccessMode(), "监控设备", null, bundle);
//                        } else {
//                            function.onCallBack(" data不能为空");
//                        }
                    } catch (Exception e) {
                        function.onCallBack(" 修改失败wb"+ e.toString());
                    }
                }
            });

        }
    }


    @Override
    public void onSwipeRefresh() {
        swipeLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(false);
                if (!StringUtils.isEmpty(url)){
                    webview.loadUrl(url);
                }
            }
        }, 2000);
    }

    @Override
    public void onPushDistanceMoreAction(int distance) {}

    @Override
    public void onPullEnableMoreAction(boolean enable) {}

}
